﻿using System;
using System.IO;
using System.Linq;
using System.Web;
using Newtonsoft.Json;

namespace Altairis.FluffyCloud.WebCore.Handlers {

    public class HeaderImageIndexHandler : IHttpHandler {

        public bool IsReusable {
            get { return false; }
        }

        public void ProcessRequest(HttpContext context) {
            // Get list of available header images
            var folderPath = context.Server.MapPath("~/Content/HeaderImages");
            var fileNames = Directory.GetFiles(folderPath, "*.jpg").Select(x => Path.GetFileName(x));
            var data = from fileName in fileNames
                       select new {
                           url = "/Content/HeaderImages/" + fileName,
                           author = fileName.Substring(0, fileName.LastIndexOf('_')).ToUpper(),
                       };

            // Send serialized response
            context.Response.Cache.SetCacheability(HttpCacheability.ServerAndPrivate);
            context.Response.Cache.SetExpires(DateTime.Now.AddHours(12));
            context.Response.ContentType = "application/json";
            context.Response.Output.Write(JsonConvert.SerializeObject(data));
        }
    }
}